<template>
  <ContentWrap>
    <el-row :gutter="20">
      <!-- 左侧：配置选择和图片上传 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>人脸识别测试</span>
          </template>
          
          <el-form :model="testForm" label-width="100px">
            <el-form-item label="选择配置">
              <el-select v-model="testForm.configId" placeholder="请选择人脸配置" style="width: 100%">
                <el-option
                  v-for="config in configList"
                  :key="config.id"
                  :label="config.name"
                  :value="config.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="上传图片">
              <el-upload
                class="upload-demo"
                drag
                :action="uploadUrl"
                :headers="uploadHeaders"
                :before-upload="beforeUpload"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :file-list="fileList"
                list-type="picture"
                accept="image/*"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 jpg/png 格式的图片文件，且不超过 10MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                @click="handleRecognize" 
                :loading="recognizing"
                :disabled="!testForm.configId || !testForm.imageUrl"
              >
                开始识别
              </el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      
      <!-- 右侧：识别结果 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>识别结果</span>
          </template>
          
          <div v-if="recognizeResult">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="识别状态">
                <el-tag :type="recognizeResult.success ? 'success' : 'danger'">
                  {{ recognizeResult.success ? '成功' : '失败' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="人脸数量">
                {{ recognizeResult.faceCount || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="错误码" v-if="!recognizeResult.success">
                {{ recognizeResult.errorCode }}
              </el-descriptions-item>
              <el-descriptions-item label="错误信息" v-if="!recognizeResult.success">
                {{ recognizeResult.errorMsg }}
              </el-descriptions-item>
            </el-descriptions>
            
            <!-- 人脸信息列表 -->
            <div v-if="recognizeResult.success && recognizeResult.faces?.length > 0" class="mt-4">
              <h4>人脸详情</h4>
              <el-table :data="recognizeResult.faces" border>
                <el-table-column label="序号" type="index" width="60" />
                <el-table-column label="位置 (x, y)" width="120">
                  <template #default="scope">
                    {{ scope.row.x }}, {{ scope.row.y }}
                  </template>
                </el-table-column>
                <el-table-column label="尺寸 (宽×高)" width="120">
                  <template #default="scope">
                    {{ scope.row.width }}×{{ scope.row.height }}
                  </template>
                </el-table-column>
                <el-table-column label="置信度" width="100">
                  <template #default="scope">
                    {{ (scope.row.confidence * 100).toFixed(2) }}%
                  </template>
                </el-table-column>
                <el-table-column label="年龄" width="80">
                  <template #default="scope">
                    {{ scope.row.age || '-' }}
                  </template>
                </el-table-column>
                <el-table-column label="性别" width="80">
                  <template #default="scope">
                    {{ scope.row.gender || '-' }}
                  </template>
                </el-table-column>
                <el-table-column label="情绪" width="100">
                  <template #default="scope">
                    {{ scope.row.emotion || '-' }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          
          <el-empty v-else description="暂无识别结果" />
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图片预览 -->
    <el-row v-if="testForm.imageUrl" class="mt-4">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>图片预览</span>
          </template>
          <div class="text-center">
            <img :src="testForm.imageUrl" alt="上传的图片" style="max-width: 100%; max-height: 400px;" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </ContentWrap>
</template>

<script setup lang="ts">
import { UploadFilled } from '@element-plus/icons-vue'
import { getFaceConfigPage, recognizeFace } from '@/api/ai/face'
import { getAccessToken } from '@/utils/auth'

/** 人脸识别测试 */
defineOptions({ name: 'AiFaceTest' })

const message = useMessage() // 消息弹窗

const configList = ref([]) // 配置列表
const recognizing = ref(false) // 识别中
const recognizeResult = ref(null) // 识别结果
const fileList = ref([]) // 文件列表

// 测试表单
const testForm = reactive({
  configId: undefined,
  imageUrl: ''
})

// 上传配置
const uploadUrl = import.meta.env.VITE_BASE_URL + '/admin-api/infra/file/upload'
const uploadHeaders = {
  Authorization: 'Bearer ' + getAccessToken()
}

/** 获取配置列表 */
const getConfigList = async () => {
  try {
    const data = await getFaceConfigPage({ pageNo: 1, pageSize: 100, status: 0 })
    configList.value = data.list
  } catch (error) {
    console.error('获取配置列表失败:', error)
  }
}

/** 上传前校验 */
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }
  if (!isLt10M) {
    message.error('上传图片大小不能超过 10MB!')
    return false
  }
  return true
}

/** 上传成功 */
const handleUploadSuccess = (response) => {
  if (response.code === 0) {
    testForm.imageUrl = response.data
    message.success('图片上传成功')
  } else {
    message.error('图片上传失败：' + response.msg)
  }
}

/** 上传失败 */
const handleUploadError = () => {
  message.error('图片上传失败')
}

/** 开始识别 */
const handleRecognize = async () => {
  if (!testForm.configId) {
    message.warning('请选择人脸配置')
    return
  }
  if (!testForm.imageUrl) {
    message.warning('请上传图片')
    return
  }
  
  recognizing.value = true
  try {
    const result = await recognizeFace({
      configId: testForm.configId,
      imageUrl: testForm.imageUrl
    })
    recognizeResult.value = result
    
    if (result.success) {
      message.success(`识别成功，检测到 ${result.faceCount} 张人脸`)
    } else {
      message.error(`识别失败：${result.errorMsg}`)
    }
  } catch (error) {
    message.error('识别请求失败')
    console.error('识别失败:', error)
  } finally {
    recognizing.value = false
  }
}

/** 重置 */
const handleReset = () => {
  testForm.configId = undefined
  testForm.imageUrl = ''
  fileList.value = []
  recognizeResult.value = null
}

/** 初始化 */
onMounted(() => {
  getConfigList()
})
</script>

<style scoped>
.upload-demo {
  width: 100%;
}
</style>